<?php
namespace model\all;
use model\cat as actBase;
use sp\db\sql\SqlWhere;

class All extends actBase{

    public function getTable(){
        $table = table('alldoc');
        $table->setRelation(Relation::getInstance()->getRatlion());
        $table->resultAsObject('model\\all\\Row');
        $table->setWhereConf('searchKey', array('tag', 'like'));
        $table->setWhereConf('_order', function(SqlWhere $where, $value){
            switch ($value) {
                case 'chapter':
                    $where->order_by('chapter', 'asc');
                    $where->order_by('id', 'asc');
                    break;
                default:
                    $where->order_by('id', 'desc');
                    break;
            }
        });

        return $table;
    }

    protected function filter($post, $isAdd = false){
        if(isset($post['fields']) && $post['fields'] && is_array($post['fields'])){
            $fields = [];
            $fieldsN = [];
            foreach ($post['fields']['k'] as $k => $item) {
                if(!$item){
                    continue;
                }

                if($desc = $post['fields']['d'][$k]){
                    $desc = urlencode($desc);
                }

                if($rule = $post['fields']['r'][$k]){
                    $rule = urlencode($rule);
                }
                $n = $post['fields']['n'][$k];

                if($n == 1){
                    $fields[] = [
                        'k' => $item,
                        'n' => $n,
                        't' => $post['fields']['t'][$k],
                        'd' => $desc,
                        'r' => $rule,
                    ];
                } else {
                    $fieldsN[] = [
                        'k' => $item,
                        'n' => $n,
                        't' => $post['fields']['t'][$k],
                        'd' => $desc,
                        'r' => $rule,
                    ];
                }

            }
            $fields = array_merge($fields, $fieldsN);
            if($fields){
                $post['fields'] = json_encode($fields);
            } else {
                $post['fields'] = '';
            }
        }
        if(!$post['tag'] && $post['api']){
            $post['tag'] = $post['api'];
        }
        if($isAdd){
            $post['sid'] = sites()->getId();
        }
        return $post;
    }

    protected function formatWhere($where){
        $where['sid'] = sites()->getId();
        return $where;
    }
}